package cc.admin.modules.sys.service.impl;

import cc.admin.common.sys.vo.LoginUser;
import cc.admin.common.util.oConvertUtils;
import cc.admin.modules.shiro.authc.ShiroRealm;
import cc.admin.modules.sys.entity.SysPermission;
import cc.admin.modules.sys.entity.SysRolePermission;
import cc.admin.modules.sys.mapper.SysRolePermissionMapper;
import cc.admin.modules.sys.service.ISysPermissionService;
import cc.admin.modules.sys.service.ISysRolePermissionService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <getPageFilterFields>
 * 角色权限表 服务实现类
 * </getPageFilterFields>
 *
 * @Author scott
 * @since 2018-12-21
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService {

    @Autowired
    private ISysPermissionService sysPermissionService;

    @Override
    public void saveRolePermission(String roleId, String permissionIds) {
        LambdaQueryWrapper<SysRolePermission> query = new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId);
        this.remove(query);
        List<SysRolePermission> list = new ArrayList<SysRolePermission>();
        String[] arr = permissionIds.split(",");
        for (String p : arr) {
            if (oConvertUtils.isNotEmpty(p)) {
                SysRolePermission rolepms = new SysRolePermission(roleId, p);
                list.add(rolepms);
            }
        }
        this.saveBatch(list);
    }

    @Override
    public void saveRolePermission(String roleId, String permissionIds, String lastPermissionIds) {
        // 删除角色权限
        this.remove(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId));
        List<String> permissionList = StrUtil.splitTrim(permissionIds,",");
        List<SysRolePermission> sysRolePermissions= new ArrayList<>();
        List<SysRolePermission> list = addParentId(roleId, permissionList,sysRolePermissions);

        this.saveBatch(list);

        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm shiroRealm = (ShiroRealm) securityManager.getRealms().iterator().next();
        //清除权限 相关的缓存
        shiroRealm.clearAllCache();

    }
    /**
    * @Description: 递归查找父级列表
    * @param p:
    * @param lastPermissionIds:
    * @param roleId:
    * @param list:
    * @Return:
    */
    private List<SysRolePermission> getParentId(String p,String lastPermissionIds,String roleId ,List<SysRolePermission> list) {
        SysPermission sysPermission = sysPermissionService.getById(p);
        if (sysPermission != null) {
            String  parentId = sysPermission.getParentId();
            if (StrUtil.isNotEmpty(parentId) && lastPermissionIds.indexOf(parentId) == -1 ) {
                SysRolePermission rolepms = new SysRolePermission(roleId, parentId);
                if(!list.contains(rolepms)) {
                    list.add(rolepms);
                }
                p = parentId;
                getParentId(parentId,lastPermissionIds,roleId,list);
            }
        }
        return list;

    }

    private  List<SysRolePermission> addParentId(String roleId,List<String> permissionList, List<SysRolePermission> list ){
        LoginUser sysUser= (LoginUser)SecurityUtils.getSubject().getPrincipal();
            List<String> permissionParentList=new ArrayList<>();
            for (String permissionId:permissionList){
                SysPermission sysPermission= sysPermissionService.getById(permissionId);
                String parentId="";
                if (sysPermission!=null){
                    parentId=sysPermission.getParentId();
                }

                if(StrUtil.isNotEmpty(parentId)){
                    if (!permissionParentList.contains(parentId)){
                        permissionParentList.add(parentId);
                    }
                }
                if (sysPermission!=null){
                    SysRolePermission sysRolePermission = new SysRolePermission(roleId, sysPermission.getId());
                    sysRolePermission.setSysOrgCode(sysUser.getCompanyCode());
                    if(!list.contains(sysRolePermission)){
                        list.add(sysRolePermission);
                    }
                }

            }
            if(permissionParentList.size()>0){
                addParentId(roleId, permissionParentList,list);
            }
        return list;
    }



    /**
     * 从diff中找出main中没有的元素
     *
     * @param main
     * @param diff
     * @return
     */
    private List<String> getDiff(String main, String diff) {
        if (oConvertUtils.isEmpty(diff)) {
            return null;
        }
        if (oConvertUtils.isEmpty(main)) {
            return Arrays.asList(diff.split(","));
        }

        String[] mainArr = main.split(",");
        String[] diffArr = diff.split(",");
        Map<String, Integer> map = new HashMap<>();
        for (String string : mainArr) {
            map.put(string, 1);
        }
        List<String> res = new ArrayList<String>();
        for (String key : diffArr) {
            if (oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) {
                res.add(key);
            }
        }
        return res;
    }

}
